<?php

namespace app\service;

use app\exception\ErrnoPlus;
use share\exception\ApiException;
use share\exception\Errno;
use share\service\UserBaseService;
use share\utils\Helper;

class OpenAppProductService{

    public static function getProductsByAppId($openAppId,$page,$size){
        $filter = [
            'open_app_id' => $openAppId,
        ];
        $ossProducts = OssProductService::getNativeAll($filter,[
            'id',
            'sku',
            'name',
            'content',
            'aliyun_cloud_storage_id',
            'price',
            'state',
            'type',
            'num',
            'created'
        ],'created DESC',$size,($page -1) * $size);
        $cloudInfos = AliyunCloudStorageService::getAll(array_column($ossProducts,'aliyun_cloud_storage_id'));
        $freeCloudInfos = AliyunCloudStorageService::getFreeAll();
        foreach($ossProducts as &$item){
            $csId = $item['aliyun_cloud_storage_id'];
            unset($item['aliyun_cloud_storage_id']);
            $type  = $item['type'];
            $num  = $item['num'];
            unset($item['num']);
            if($type == OssProductService::TYPE_OF_FREE){
                $cloudInfo = Helper::filterOne($freeCloudInfos,['id' => $csId]);
            }
            else{
                $cloudInfo = Helper::filterOne($cloudInfos,['id' => $csId]);
            }
            $months = $cloudInfo['months'];
            if($type == OssProductService::TYPE_OF_COMPOSER){
                $months = $months * $num; 
            }
            $item['attr'] = [
                'recordType' => $cloudInfo['record_type'],
                'lifecycle' => $cloudInfo['lifecycle'],
                'months' => $months,
                'site' => $cloudInfo['site'],
            ];
        }

        $count = OssProductService::count($filter);
        return [
            'list' => $ossProducts,
            'total' => $count,
        ];
    }

    public static function getFreeProduct($openAppId,$sn,$sku,$userId){
        $iotId = self::checkGetFreeProductParams($openAppId,$sn,$sku,$userId);
        $projectId = AliyunService::getDefaultProjectId();
        $site = 'CN';
        $handle = AliyunService::instance($projectId,$site);
        return $handle->getFreeCloudStorage($iotId);
    }

    public static function buyFreeProduct($openAppId,$sn,$sku,$userId){
        $iotId = self::checkGetFreeProductParams($openAppId,$sn,$sku,$userId);
        $projectId = AliyunService::getDefaultProjectId();
        $site = 'CN';
        $handle = AliyunService::instance($projectId,$site);
        return $handle->consumeFreeCloudStorage($iotId);
    }

    public static function checkGetFreeProductParams($openAppId,$sn,$sku,$userId){
        $product = OssProductService::getByFilter([
            'sku' => $sku,
            'open_app_id' => $openAppId,
            'type' => OssProductService::TYPE_OF_FREE,
            'state' => OssProductService::STATE_OF_ON_SHELF,
        ]);
        if(empty($product)){
            throw new ApiException("套餐不存在或者已不可用 sku:{$sku}",Errno::COMMON_INVALID_INPUT);
        }

        $userInfo = UserBaseService::getByUserId($userId);
        if(empty($userInfo)){
            throw new ApiException("下单用户不存在 {$userId}",Errno::COMMON_INVALID_INPUT);
        }
        $uid = $userInfo['id'];
        $deviceBase = DeviceBaseService::getUsefulOssSn($sn);
        if(empty($deviceBase) || empty($deviceBase['iot_id'])){
            throw new ApiException("设备不存在或者参数已丢失",Errno::COMMON_INVALID_INPUT);
        }
        $iotId = $deviceBase['iot_id'];        
        $userBind = UserDeviceBindingService::getBindingInfoByIotId($iotId);
        if($userBind == null){
            throw new ApiException("未找到 iotId:{$iotId} 相关的信息.",ErrnoPlus::INVALID_PARAM);
        }
        if($userBind['uid'] != $uid){
            throw new ApiException("用户{$uid}不能为设备 iotId:{$iotId} 购买套餐.",ErrnoPlus::INVALID_PARAM);
        }
        return $iotId;
    }

}